package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.adapter.FruitAdapter;

import java.util.ArrayList;

public class FruitListViewActivity extends AppCompatActivity {
    private ListView listView;
    private ArrayList<Fruit> fruitList = new ArrayList<Fruit>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fruit_list_view);

        listView = findViewById(R.id.fruit_list_view);

        //自定义一个适配器
        initFruit();
        initView();
    }

    private void initView() {
        FruitAdapter adapter = new FruitAdapter(FruitListViewActivity.this,
                R.layout.list_item,fruitList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               // Fruit fruit = fruitList.get(position);
                //Toast.makeText(FruitListViewActivity.this,fruit.getName()+" position: "+position, Toast.LENGTH_SHORT).show();

                TextView tvName = view.findViewById(R.id.fruit_name);
                String name = tvName.getText().toString();
                Toast.makeText(FruitListViewActivity.this, "name:"+name+"-position"+position, Toast.LENGTH_SHORT).show();
            }
        });
    }

    //初始化水果数据
    private void initFruit() {
        for(int i=0;i<2;i++){
            Fruit apple = new Fruit("Apple",R.drawable.apple_pic);
            fruitList.add(apple);
            Fruit banana = new Fruit("Banana",R.drawable.banana_pic);
            fruitList.add(banana);
            Fruit orange = new Fruit("Orange",R.drawable.orange_pic);
            fruitList.add(orange);
            Fruit pear = new Fruit("Pear",R.drawable.pears_pic);
            fruitList.add(pear);
            Fruit pineapple = new Fruit("Pineapple",R.drawable.pineapple_pic);
            fruitList.add(pineapple);
            Fruit strawberry = new Fruit("Strawberry",R.drawable.strawberry_pic);
            fruitList.add(strawberry);
            Fruit tomato = new Fruit("Tomato",R.drawable.tomato_pic);
            fruitList.add(tomato);
            Fruit watermelon = new Fruit("Watermelon",R.drawable.watermelon_pic);
            fruitList.add(watermelon);
            fruitList.add(strawberry);
            Fruit tomato1= new Fruit("Tomato",R.drawable.tomato_pic);
            fruitList.add(tomato1);
            Fruit watermelon1 = new Fruit("Watermelon",R.drawable.watermelon_pic);
            fruitList.add(watermelon1);
        }
    }

}